package sa.com.sure.ejtimaa;

import sa.com.sure.ejtimaa.R;
import sa.com.sure.ejtimaa.common.AppConstants;
import sa.com.sure.ejtimaa.common.AppPreferences;
import sa.com.sure.ejtimaa.common.Helper;
import sa.com.sure.ejtimaa.webservice.DataWebService;
import sa.com.sure.ejtimaa.database.Members;
import sa.com.sure.ejtimaa.model.MemberInfo;


import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class LoginActivity extends BaseActivity {
    /** Called when the activity is first created. */
	
	
	
	
	private EditText etUserName = null;
	private EditText etPassword = null;
	
	private String userName = "";
	private String password = "";
	private boolean isAuthenticated = false;
	
	ProgressDialog progressDialog = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try
    	{
	        super.onCreate(savedInstanceState);
	        
	        isAuthenticated = AppPreferences.Instance.getData(AppConstants.IsAuthenticated).equals("true");
	        if(isAuthenticated){	        		        
	        	login();
	        }               
	        setContentView(R.layout.login);
		}
		catch(Exception ex){    		
	    	Helper.HandleError(ex,true);
		}
    }
        
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
	    try
	    {
	        MenuInflater menuInflater = getMenuInflater();
	        menuInflater.inflate(R.menu.login_options_menu, menu);
		}
		catch(Exception ex){    		
	    	Helper.HandleError(ex,true);
		}
        
        return true;                
    }
    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	try
    	{
	    	switch (item.getItemId())
	        {
	        case R.id.imenu_settings:
	        	Helper.StartActivity(SettingActivity.class);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);        	
	        }
    	
		}
		catch(Exception ex){    		
	    	Helper.HandleError(ex,true);
		}
		return false;  
    }
    
    
    public void OnLogin(View view) throws Exception  {    
    	 
    	try	
    	{
            etUserName = (EditText)findViewById(R.id.etUserName);
        	etPassword = (EditText)findViewById(R.id.etPassword); 
    		
    		userName = etUserName.getText().toString();
    	   	password = etPassword.getText().toString();
    		
    		if(checkValidation())
        	{ 	    	   	
	    		
	    	   	AppPreferences.Instance.setData(AppConstants.UserName, userName);
	    	   	AppPreferences.Instance.setData(AppConstants.Password, password);
	    	   	
	            progressDialog  = ProgressDialog.show(this,getString(R.string.PleaseWati), getString(R.string.RetrievingData), true);
	            
	    		 new Thread(new Runnable() {
	    			 public void run() {
	    			try {
	    				
							isAuthenticated  = DataWebService.Instance.Authenticate(userName, password);
														
							if(!isAuthenticated){
								handler.sendMessage(handler.obtainMessage(RESULT_CANCELED));
							}
							else{
								
								MemberInfo member =  DataWebService.Instance.GetMember(userName);
								
								if(Members.Instance.GetItemByUserName(userName)==null)
								{									
									Members.Instance.addItem(member);
								}
								else
								{
									Members.Instance.updateItemByUserName(member);
								}								
								
								handler.sendMessage(handler.obtainMessage(RESULT_OK));								
							}
							 
						} catch (Exception ex) {						
							handler.sendMessage(handler.obtainMessage());
					    	Helper.HandleError(ex);
						}
	    			 }
	    		 }).start();
         }           	    	   
    		
    	}
    	catch(Exception ex){    		
	    	Helper.HandleError(ex,R.string.WebServiceURLNotValid);
    	}
    	    	   
    }
    
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
        	        
        	progressDialog.dismiss();
        	
        	if(msg.what==RESULT_OK)
        		login();
        	else     
        	{
        		if(msg.what==RESULT_CANCELED)
        		{

	        		Helper.ShowToast(R.string.UserNameOrPasswordIsWrong);
        		}
        		else
        		{
        			Helper.ShowToast(R.string.GlobalError);
        			
        		}
        	}
        }
    };
    
    private boolean checkValidation(){
    	
    	boolean result = true;
    	    	
    	if(userName.length()==0){
    		
    		etUserName.setError(getString(R.string.PleaseEnterUserName));
    		result = false;
    	}
    	
     	if(password.length()==0){
    		
     		etPassword.setError(getString(R.string.PleaseEnterPassword));
    		result = false;
    	}   	
     	
    	return result;
    }
    
    private void login(){
    	    	       		    			
			AppPreferences.Instance.setData(AppConstants.IsAuthenticated, "true");
			this.finish();
			Helper.StartActivity(MainActivity.class);		
		
    }
}